<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class BaseCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'unused:base-command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'BaseCommand Class.';

    /**
     * The action name of the console job.
     *
     * @var string
     */
    protected $action = '';

    /**
     * The unique code for logger
     *
     * @var string
     */
    protected $uid = '';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->uid = uniqid();
        //$this->logger('[ENTER]');
        set_time_limit(0);
    }

    /**
     * Before execute the console command.
     *
     * @return mixed
     * @throws \Exception
     */
    public function handle()
    {
        if (!$this->uid) {
            $this->uid = uniqid();
        }
        $options = $this->options();
        $this->action = getVal($options, 'action', 'handler');
        $this->logger("[START]");
        try {
            $res = $this->handler();
        } catch (\Exception $e) {
            $error = [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'file' => $e->getFile() . ' : ' . $e->getLine(),
                'type' => 'command',
                'uid' => $this->uid,
            ];
            $this->logger("[EXCEPTION] - " . json_encode($error, JSON_UNESCAPED_UNICODE));
            $this->logger("[END]");
            throw new \Exception($error['msg'] . ' @file: ' . $error['file'], $error['code']);
        }
        $this->logger("[END] - res : " . json_encode($res, JSON_UNESCAPED_UNICODE));
        return true;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handler()
    {
        return true;
    }

    /**
     * log info
     * @param $msg
     * @return bool
     */
    protected function logger($msg)
    {
        $signature = explode(' ', $this->signature, 2);
        $signature = $signature[0];
        $msg = "[CMD][{$signature}][{$this->action}] - [{$this->uid}] - " . $msg;
        if ($this->output) {
            $this->line("[".date('Y-m-d H:i:s')."]" . $msg);
        }
        Log::info($msg);
        return true;
    }

}